<template>
  <div class="common-layout">
    <el-container>
      <el-header>
      </el-header>
      <el-container>
        <el-aside width="200px" class="sidebar">
          <div class="sidebar-header">
            <h3>管理员功能</h3>
          </div>
          
          <div class="sidebar-menu" v-if="authStore.isLoggedIn">
            <button 
              @click="activeTab = 'changePassword'" 
              :class="{ active: activeTab === 'changePassword' }" 
              class="menu-item"
            >修改密码</button>
            <button 
              @click="activeTab = 'audit'" 
              :class="{ active: activeTab === 'audit' }" 
              class="menu-item"
            >审核资质</button>
            <button 
              @click="activeTab = 'users'" 
              :class="{ active: activeTab === 'users' }" 
              class="menu-item"
            >查看所有用户</button>
          </div>
          
          <div v-else class="sidebar-login-prompt">
            <button @click="goHome" class="back-home-tab">前往登录</button>
          </div>
          
          <!-- 侧边栏底部退出按钮 -->
          <div class="sidebar-footer" v-if="authStore.isLoggedIn">
            <button @click="handleLogout" class="logout-btn">退出登录</button>
          </div>
          
        </el-aside>
        
        <el-main class="main-content">
          <!-- 修改密码表单 -->
          <div v-if="activeTab === 'changePassword'" class="business-card">
            <h3>修改密码</h3>
            <form @submit.prevent="handleChangePassword" class="password-form">
              <div class="form-group">
                <label>账号:</label>
                <input v-model="changePasswordForm.accountId" placeholder="账号" required>
              </div>
              <div class="form-group">
                <label>旧密码:</label>
                <input v-model="changePasswordForm.oldPassword" type="password" placeholder="旧密码" required>
              </div>
              <div class="form-group">
                <label>新密码:</label>
                <input v-model="changePasswordForm.newPassword" type="password" placeholder="新密码" required>
              </div>
              <button type="submit" class="submit-btn">修改密码</button>
            </form>
          </div>
          
          <!-- 审核资质 -->
          <div v-if="activeTab === 'audit'" class="business-card">
            <h3>审核资质</h3>
            
            <!-- 分页信息 -->
            <div class="pagination-info">
              <span>共 {{ pagination.total }} 条记录</span>
              <span>第 {{ pagination.currentPage }} 页 / 共 {{ Math.ceil(pagination.total / pagination.pageSize) }} 页</span>
            </div>
            
            <div v-if="paginatedUsers.length > 0" class="users-table">
              <table>
                <thead>
                  <tr>
                    <th>账号</th>
                    <th>用户类型</th>
                    <th>资质状态</th>
                    <th>审核资料</th>
                    <th>注册时间</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="user in paginatedUsers" :key="user.accountId">
                    <td>{{ user.accountId }}</td>
                    <td>{{ getUserTypeName(user.accountType) }}</td>
                    <td>{{ user.status === 1 ? '已审核' : '未审核' }}</td>
                    <td>{{ user.qualificationContent || '无' }}</td>
                    <td>{{ formatDate(user.createdAt) }}</td>
                    <td>
                      <button 
                        v-if="user.status === 0" 
                        @click="handleAudit(user.accountId)" 
                        class="audit-btn"
                      >
                        通过
                      </button>
                      <span v-else class="audited-text">已审核通过</span>
                    </td>
                  </tr>
                </tbody>
              </table>
              
              <!-- 分页控件 -->
              <div class="pagination-controls" v-if="pagination.total > pagination.pageSize">
                <button 
                  @click="prevPage"
                  :disabled="pagination.currentPage === 1"
                  class="pagination-btn"
                >
                  &lt; 上一页
                </button>
                
                <span class="page-info">
                  第 {{ pagination.currentPage }} 页 / 共 {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
                </span>
                
                <button 
                  @click="nextPage"
                  :disabled="pagination.currentPage === Math.ceil(pagination.total / pagination.pageSize)"
                  class="pagination-btn"
                >
                  下一页 &gt;
                </button>
              </div>
            </div>
            <p v-else class="no-data">没有用户数据</p>
          </div>
          
          <!-- 查看所有用户 -->
          <div v-if="activeTab === 'users'" class="business-card">
            <h3>所有用户</h3>
            <div v-if="users.length > 0" class="users-table">
              <table>
                <thead>
                  <tr>
                    <th>账号</th>
                    <th>用户类型</th>
                    <th>资质状态</th>
                    <th>注册时间</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="user in users" :key="user.accountId">
                    <td>{{ user.accountId }}</td>
                    <td>{{ getUserTypeName(user.accountType) }}</td>
                    <td>{{ user.qualificationProof === 1 ? '已审核' : '未审核' }}</td>
                    <td>{{ formatDate(user.createdAt) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <p v-else class="no-data">没有用户数据</p>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { useAuthStore } from '../stores/auth'
import ApiService from '../services/api'
import { useRouter } from 'vue-router'

export default {
  name: 'AdminView',
  setup() {
    const authStore = useAuthStore()
    const router = useRouter()
    return { authStore, router }
  },
  data() {
    return {
      activeTab: 'audit',
      changePasswordForm: {
        accountId: '',
        oldPassword: '',
        newPassword: ''
      },
      users: [],
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      apiService: new ApiService('admin')
    }
  },
  mounted() {
    this.authStore.initAuth()
    if (this.authStore.isLoggedIn) {
      this.activeTab = 'audit'
      this.changePasswordForm.accountId = this.authStore.accountId
      this.loadUsers()
    }
  },
  computed: {
    paginatedUsers() {
      const startIndex = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const endIndex = startIndex + this.pagination.pageSize
      return this.users.slice(startIndex, endIndex)
    }
  },
  methods: {
    async handleChangePassword() {
      try {
        const result = await this.apiService.changePassword(
          this.changePasswordForm.accountId,
          this.changePasswordForm.oldPassword,
          this.changePasswordForm.newPassword
        )
        alert(result.message)
      } catch (error) {
        alert('修改密码出错')
      }
    },
    
    async loadUsers() {
      try {
        const result = await this.apiService.getAllUsers()
        if (result.message === '查询成功') {
          this.users = result.data || []
          this.pagination.total = this.users.length
        }
      } catch (error) {
        console.error('加载用户列表出错:', error)
      }
    },
    
    async handleAudit(accountId) {
      try {
        const result = await this.apiService.auditQualification(accountId)
        alert(result.message)
        if (result.message === '审核成功') {
          this.loadUsers()
        }
      } catch (error) {
        alert('审核出错')
      }
    },
    
    getUserTypeName(type) {
      const typeMap = {
        0: '生产商',
        1: '经销商',
        2: '平台',
        3: '物流商',
        4: '消费者',
        5: '管理员'
      }
      return typeMap[type] || type
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN')
    },
    
    handleLogout() {
      this.authStore.setLogout()
      this.activeTab = 'audit'
      this.users = []
      this.pagination.currentPage = 1
      this.pagination.total = 0
      this.router.push('/')
    },
    
    goHome() {
      try { this.$router.push('/') } catch (e) { window.location.href = '/' }
    },
    
    prevPage() {
      if (this.pagination.currentPage > 1) {
        this.pagination.currentPage--
      }
    },
    
    nextPage() {
      const totalPages = Math.ceil(this.pagination.total / this.pagination.pageSize)
      if (this.pagination.currentPage < totalPages) {
        this.pagination.currentPage++
      }
    }
  }
}
</script>

<style scoped>
/* 新色彩主题 */
:root {
  --primary-color: #409EFF;
  --primary-light: #ecf5ff;
  --primary-dark: #3375b9;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --text-primary: #2c3e50;
  --text-regular: #5a6c7d;
  --text-secondary: #8796a8;
  --text-placeholder: #c0c8d1;
  --bg-gradient: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  --bg-card: #ffffff;
  --bg-sidebar: linear-gradient(180deg, #304156 0%, #1f2d3d 100%);
  --border-color: #e4e7ed;
  --border-light: #ebeef5;
  --border-lighter: #f2f6fc;
  --shadow-card: 0 4px 20px rgba(0, 0, 0, 0.08);
  --shadow-hover: 0 6px 24px rgba(0, 0, 0, 0.1);
  --shadow-header: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 整体布局 */
.common-layout {
  height: 100vh;
  width: 100vw;
  background: var(--bg-gradient);
}

.el-container {
  height: 100%;
}

/* 顶部导航栏 */
.el-header {
  background: #ffffff;
  box-shadow: var(--shadow-header);
  display: flex;
  align-items: center;
  padding: 0 24px;
  border-bottom: 1px solid var(--border-color);
  height: 0px;
  line-height: 60px;
}

/* 侧边栏 */
.el-aside {
  background: var(--bg-sidebar);
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.1);
  overflow-y: auto;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #2d3a4b;
  color: white;
  text-align: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.sidebar-menu {
  padding: 16px 0;
}

.menu-item {
  width: 100%;
  padding: 12px 24px;
  border: none;
  background: transparent;
  color: rgba(255, 255, 255, 0.7);
  text-align: left;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  display: block;
}

.menu-item:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.menu-item.active {
  background: var(--primary-color);
  color: #ffffff;
}

.sidebar-login-prompt {
  padding: 20px;
  text-align: center;
}

.back-home-tab {
  padding: 10px 20px;
  margin: 10px auto;
  border: 1px solid var(--primary-color);
  background: transparent;
  color: var(--primary-color);
  cursor: pointer;
  display: block;
  width: 100%;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.back-home-tab:hover {
  background: var(--primary-color);
  color: white;
}

.sidebar-footer {
  margin-top: auto;
  margin-top: 300%;
  padding: 16px;
  width: 100%;
  box-sizing: border-box;
}

.logout-btn {
  width: 80%;
  margin: 0 auto;
  display: block;
  padding: 10px 20px;
  border: none;
  background: var(--danger-color);
  color: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background: #e4393c;
}

/* 主内容区 */
.el-main {
  padding: 24px;
  overflow-y: auto;
  background: transparent;
}

.main-content {
  min-height: 100%;
}

/* 业务卡片 */
.business-card {
  background: var(--bg-card);
  border-radius: 8px;
  box-shadow: var(--shadow-card);
  padding: 24px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: 1px solid var(--border-light);
}

.business-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-hover);
}

.business-card h3 {
  color: var(--text-primary);
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
}

/* 表单样式 */
.password-form {
  max-width: 500px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: var(--text-regular);
}

.form-group input, .form-group textarea, .form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

.form-group input:focus, .form-group textarea:focus, .form-group select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.submit-btn {
  width: 100%;
  padding: 10px;
  background: var(--success-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.submit-btn:hover {
  background: #5daf34;
}

/* 分页样式 */
.pagination-info {
  margin-bottom: 1rem;
  padding: 0.5rem;
  background: var(--border-lighter);
  border-radius: 4px;
  font-size: 14px;
  color: var(--text-regular);
}

.pagination-info span {
  margin-right: 1rem;
}

.pagination-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  margin-top: 2rem;
  padding: 1rem;
  background: var(--border-lighter);
  border-radius: 8px;
  border: 1px solid var(--border-color);
  flex-wrap: wrap;
}

.pagination-btn {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  background: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.pagination-btn:hover:not(:disabled) {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.pagination-btn:disabled {
  background: var(--border-lighter);
  color: var(--text-placeholder);
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: var(--text-regular);
  font-weight: bold;
}

/* 表格样式 */
.users-table {
  overflow-x: auto;
  margin-bottom: 1rem;
}

.users-table table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border-radius: 8px;
  overflow: hidden;
}

.users-table th,
.users-table td {
  border: 1px solid var(--border-color);
  padding: 12px;
  text-align: left;
  word-wrap: break-word;
}

.users-table th {
  background-color: var(--border-lighter);
  font-weight: bold;
  color: var(--text-primary);
}

.users-table tr:nth-child(even) {
  background-color: var(--border-lighter);
}

.users-table tr:hover {
  background-color: var(--border-light);
}

.audit-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  width: 100%;
  height: 30px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.audit-btn:hover {
  background: var(--primary-dark);
}

.audited-text {
  color: var(--success-color);
  font-weight: bold;
  text-align: center;
  display: block;
  height: 30px;
  line-height: 30px;
}

.no-data {
  text-align: center;
  padding: 2rem;
  color: var(--text-secondary);
  font-style: italic;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-container {
    grid-template-columns: 1fr;
    grid-template-rows: 60px 1fr;
    grid-template-areas: 
      "header"
      "main";
  }
  
  .el-aside {
    display: none;
  }
  
  .el-main {
    padding: 16px;
  }
  
  .business-card {
    padding: 16px;
  }
  
  .pagination-controls {
    flex-direction: column;
    gap: 0.5rem;
  }
}
</style>